﻿using AutoMapper;
using BaseData.API.Write.Applications.Commands;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Write.Applications.CommandHandlers
{
    /// <summary>
    /// 添加权限
    /// </summary>
    public class UpdPermissionCommandHandler : IRequestHandler<UpdPermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Permission> perRep;
        private readonly IMapper mapper;

        public UpdPermissionCommandHandler(IBaseRepository<Permission> perRep,
            IMapper mapper)
        {
            this.perRep = perRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(UpdPermissionCommand request, CancellationToken cancellationToken)
        {
            var count = await perRep.GetAll().CountAsync(x => x.PermissionId != request.PermissionId&&x.PermissionName==request.PermissionName);
            if (count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.添加失败,
                    Message = "该权限已存在!!!",
                    Data = -1
                };
            }

            ApiResult<int> result = new ApiResult<int>();
            result.Code=ApiEnum.修改成功;
            result.Message = ApiEnum.修改成功.ToString();

           var per=mapper.Map<Permission>(request);
            per.CreateTime = DateTime.Now;
            await perRep.UpdateAsync(per);
            result.Data = 1;

            return await Task.FromResult(result);
        }
    }
}
